<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/8/28
 * Time: 17:41
 */

namespace App\Http\Controllers\API\ClassGroup;


use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\ClassGroup;
use App\Models\ElectiveStudent;
use App\Models\Student;
use App\Models\StudentGroup;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StudentGroupController extends Controller
{
    public function join(Request $request)
    {
        $class_id = $request->get('class_id', '');
        $open_id = $request->get('open_id', '');
        try {
            $student = Student::query()->where(['wx_key' => $open_id])->first();
            if (!$student) {
                throw new \Exception('未找到该学生');
            }
            $c_student = ElectiveStudent::query()->where(['student_code' => $student->u_code])->first();
            if (!$c_student) {
                throw new \Exception('不具备选课资格');
            }
            $class = ClassGroup::query()->where(['id' => $class_id])->first();
            if (!$class) {
                throw new \Exception('未找到该课组');
            }

            $log = new StudentGroup();
            $log->class_group_id = $class->id;
            $log->student_id = $c_student->id;
            if (!$log->save()) {
                throw new \Exception('选课记录添加失败');
            }
            $id = $log->id;
            $logs =  StudentGroup::with('user', 'classes')
                ->whereHas('classes', function ($query) use ($class) {
                    $query->where(['selection_id'=>$class->selection_id]);
                })
                ->where(['student_id' => $c_student->id])->
                where('id','<',$id)->count();
            if ($logs) {
                $log->delete();
              //  throw new \Exception('您已报名过该类课程');
            }
            $number = DB::table('student_groups')->where(['class_group_id' => $class->id])
                ->where('id','<',$id)->count();
            if ($class->peoples <= $number) {
                $log->delete();
              //  throw new \Exception('该课程已经满员');
            }
            $res['class_id'] =  $id;
            return ['success' => 'true', 'message' => '回调信息', 'data' => $res];
        } catch (\Exception $e) {
            return response(['success' => 'false', 'message' => $e->getMessage()], 406);
        }
    }

    public function check(Request $request)
    {
        $class_id = $request->get('class_id', '');
        $open_id = $request->get('open_id', '');
        try {
            $student = Student::query()->where(['wx_key' => $open_id])->first();
            if (!$student) {
                throw new \Exception('未找到该学生');
            }
            $c_student = ElectiveStudent::query()->where(['student_code' => $student->u_code])->first();
            if (!$c_student) {
                throw new \Exception('不具备选课资格');
            }
            $log =  DB::table('student_groups')->where('id',$class_id)->first();
            if(!$log){
                throw new \Exception('选课失败');
            }
            return ['success' => 'true', 'message' => '选课成功'];

        } catch (\Exception $e) {
            return response(['success' => 'false', 'message' => $e->getMessage()], 406);
        }
    }

    public function getUsersLog(Request $request)
    {
        $open_id = $request->get('open_id', '');
        try{
            $student =  Student::query()->where(['wx_key' => $open_id])->first();
            if (!$student) {
                throw new \Exception('未找到该学生');
            }
            $c_student = ElectiveStudent::query()->where(['student_code'=>$student->u_code])->first();
            if(!$c_student){
                throw new \Exception('不具备选课资格');
            }
            $logs = StudentGroup::query()->where(['student_id'=>$c_student->id])->get();
            if(!$logs){
                throw new \Exception('尚未选课');
            }
            foreach ($logs as $log){
            $class = ClassGroup::query()->where(['id'=> $log->class_group_id])->first();
                $res['student']=$c_student->student_name;
                $res['class']=$class->class_group_name;
                $res['class_number']=$class->class_group_number;
                $result[]=$res;
            }
            return ['success' => 'true', 'message' => '选课结果','data'=>$result];
        }catch (\Exception $e){
            return response(['success' => 'false', 'message' => $e->getMessage()], 406);
        }
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = StudentGroup::with('user', 'classes')
            ->whereHas('classes', function ($query) use ($queryString) {
                $query->where('class_group_name', 'like', '%' . $queryString . '%');
            })
            ->paginate();
        return $models;
    }


    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new StudentGroup();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Request $request)
    {
        $id = $request->get('id');
        $StudentGroup = $this->findModel($id);
        $StudentGroup->fill($request->all());
        if ($StudentGroup->save()) {
            return $StudentGroup;
        } else {
            return response($StudentGroup->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        $class = ClassGroup::query()->where(['id' => $model->class_group_id])->first();
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除学生学科结果。';
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $class->selected -= 1;
            $class->save();
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show(StudentGroup $StudentGroup)
    {
        return $StudentGroup;
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = StudentGroup::findOrFail($id);
        return $model;
    }
}